import {IBaseInfo,IloginResponse} from "@/@types/main"
import  {loginWaySwitch} from "@/login-handle"
import {post} from "@/api/base"
// 在页面上只需运行一次这块代码，用于统一派发 locationchange 事件
declare global {
  interface Window {
    __locationChangeSetup: boolean;
  }
}
(function setupLocationChangeEvent() {
  if (window.__locationChangeSetup) return;
  window.__locationChangeSetup = true;

  const dispatch = () => {
    // 等一下让 SPA 框架有机会更新 DOM（按需改为 requestAnimationFrame）
    setTimeout(() => {
      window.dispatchEvent(new Event('locationchange'));
    }, 0);
  };

  const _push = history.pushState;
  history.pushState = function (...args) {
    const res = _push.apply(this, args);
    dispatch();
    return res;
  };

  const _replace = history.replaceState;
  history.replaceState = function (...args) {
    const res = _replace.apply(this, args);
    dispatch();
    return res;
  };

  window.addEventListener('popstate', dispatch);
  window.addEventListener('hashchange', dispatch);
})();
export function onRouteChange(callback:Function=()=>{}) {
  const handler = () => {
    // 回调可以接收到当前 URL 或其它需要的信息
    callback(location.href);
  };
  window.addEventListener('locationchange', handler);
  // 可选：马上调用一次以处理初始加载
  // handler();
  return () => {
    window.removeEventListener('locationchange', handler);
  };
}

// http://10.1.1.3:5244/@login?redirect=%2F
const currentDomain = location.host;
console.log(`当前域名: ${currentDomain}`);
// 通过域名拿到基础信息 只允许内网访问
const user = "wac"
async function getBaseInfoByDomain() {
  
  // 这里可以根据实际需求进行调整
  const response = await post( "/loginInfo/get", { user, site: currentDomain });
  const data:{Data:IloginResponse}= response;
  const Data = data.Data;
  const currentData = {
    domain: location.origin,
    site: Data.site,
    loginPage: Data.loginPage || `${currentDomain}/login`,
    token: Data.token
  };
  return currentData;
}

// 防抖
const debounce = (func: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout;
  return (...args: any[]) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func(...args);
    }, delay);
  };
};

// 判断是否是登录页面
function checkIsLoginPage() {
  // if (baseInfo.loginPage) {
  //   return location.href.indexOf(baseInfo.loginPage) > -1;
  // }
  return location.href.indexOf("login") > -1;
}

// 处理login
async function handleLogin() {
  
  if (checkIsLoginPage()) {
    const baseInfo = await getBaseInfoByDomain();
    console.log(`baseInfo`, baseInfo);
    console.log("is login page")
    
    loginWaySwitch(baseInfo)
    // 去首页
    // location.href = baseInfo.domain;
    // location.reload();
  }
}
// 默认
const debounceHandleLogin = debounce(handleLogin, 300);
debounceHandleLogin();
// // 监听
const off = onRouteChange((href:string) => {
  console.log('路由发生变化，当前 URL：', href);
  debounceHandleLogin();
  // 在这里处理你需要的逻辑，例如重新初始化页面上的监听或行为
});